package com.eduardcapell.lopodder.io;

import java.util.Iterator;
import java.util.List;

import com.eduardcapell.lopodder.beans.FeedElement;
import com.eduardcapell.lopodder.db.DBAccess;

public class DownloadThread extends Thread {

	
	private List<FeedElement> elements; 
	private static DownloadThread theInstance = null;
	
	private DownloadThread(List<FeedElement> elements) {
		super();
		this.elements = elements;
	}
	
	public static DownloadThread getInstance(List<FeedElement> feeds) throws Exception {
		if (theInstance == null) {
			theInstance = new DownloadThread(feeds);
		}
		
		if (DownloadLock.downloading) {
			throw new Exception("A download process is already running");
		}
		
		return theInstance;
	}
	
	@Override
	public void run() {
		Iterator<FeedElement> it = elements.iterator();
		int n = 0;
        DownloadLock.downloading = true;
		
		while (it.hasNext()) {
			FeedElement fe = it.next();
			try {
				System.out.println("Downloading item " + ++n + " of " + elements.size());
				IOUtils.downloadItem(fe);
				fe.setDownloaded(true);
			} catch (Exception e) {
				e.printStackTrace();
			}

			DBAccess.updateFeedElement(fe);
		}
		
		DownloadLock.downloading = false;
		DownloadThread.theInstance = null;
		System.out.println("Finished downloading " + n + " elements.");
    }
    
}
